const crypto = require("crypto");
const DecryptType = "aes-256-gcm";
const transform = function (e: string) {
    let t = (e + "=".repeat((4 - (e.length % 4)) % 4)).replace(/-/g, "+").replace(/_/g, "/");
    let n = Buffer.from(t, "base64").toString("binary");
    let r = Buffer.alloc(n.length);
    for (let o = 0; o < n.length; ++o) {
        r[o] = n.charCodeAt(o);
    }
    return r;
};

// 解密
const decode = async (data: Buffer, salt: string, secret: string) => {
    let key = crypto.createSecretKey(transform(secret));
    let decipher = crypto.createDecipheriv(DecryptType, key, transform(salt));
    let authTagLength = 16;
    let encryptedData = Buffer.concat([data.subarray(0, data.length - authTagLength)]);
    let authTag = data.subarray(data.length - authTagLength);
    decipher.setAuthTag(authTag);
    let decrypted = Buffer.concat([decipher.update(encryptedData), decipher.final()]);
    return decrypted;
};

export { decode };
